<template>
  <div class="permissions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
      </div>
      </template>

      <!-- 搜索和筛选 -->
        <div class="search-section">
        <el-input
          v-model="searchQuery"
              placeholder="搜索权限名称、权限码、URL..."
          style="width: 300px; margin-right: 16px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="typeFilter" placeholder="全部类型" style="width: 120px; margin-right: 16px;" clearable @clear="typeFilter = null">
          <el-option label="菜单权限" :value="0" />
          <el-option label="按钮权限" :value="1" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="全部状态" style="width: 120px;" clearable @clear="statusFilter = null">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </div>

      <el-table :data="filteredPermissions" style="width: 100%" v-loading="loading">
        <el-table-column label="权限名称" min-width="200">
          <template #default="{ row }">
            <div>
              <div style="font-weight: 500;">{{ row.permissionName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限编码" width="150">
          <template #default="{ row }">
            <el-text code>{{ row.permissionCode }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="权限URL" min-width="200">
          <template #default="{ row }">
            <el-text v-if="row.url" type="info">{{ row.url }}</el-text>
            <el-text v-else type="info" style="color: #999;">-</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editPermission(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deletePermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑权限' : '新增权限'" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="form.permissionName" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限码" prop="permissionCode">
          <el-input v-model="form.permissionCode" placeholder="请输入权限码" />
        </el-form-item>
        <el-form-item label="权限URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入权限URL" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">菜单权限</el-radio>
            <el-radio :label="1">按钮权限</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级权限" clearable>
            <el-option label="无父级权限" value="" />
            <el-option 
              v-for="parent in parentPermissions" 
              :key="parent.id" 
              :label="parent.permissionName" 
              :value="parent.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { 
  sysPermissionQueryAPI, 
  sysPermissionCreateAPI, 
  sysPermissionUpdateAPI, 
  sysPermissionDeleteAPI 
} from '@/apis/sysAPI'

// 响应式数据
const searchQuery = ref('')
const typeFilter = ref(null)  
const statusFilter = ref(null)  
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const editingPermission = ref(null)

// 表单数据
const form = ref({
  permissionName: '',
  permissionCode: '',
  url: '',
  type: 0,  // 改为数字类型
  parentId: '',
  status: 1  // 改为数字类型
})

// 表单验证规则
const rules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限码', trigger: 'blur' }
  ],
  url: [
    { required: false, message: '请输入权限URL', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}


// 权限数据
const permissions = ref([])


// 计算属性
const filteredPermissions = computed(() => {
  let filtered = permissions.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(permission => 
      permission.permissionName.toLowerCase().includes(query) ||
      permission.permissionCode.toLowerCase().includes(query) ||
      (permission.url && permission.url.toLowerCase().includes(query))
    )
  }

  // 类型过滤
  if (typeFilter.value !== null) {
    filtered = filtered.filter(permission => permission.type == typeFilter.value)
  }

  // 状态过滤
  if (statusFilter.value !== null) {
    filtered = filtered.filter(permission => permission.status == statusFilter.value)
  }

  return filtered
})

const parentPermissions = computed(() => {
  return permissions.value.filter(p => p.type === 0 && p.status === 1)
})

// 方法

const getTypeText = (type) => {
  const typeMap = {
    0: '菜单权限',
    1: '按钮权限'
  }
  return typeMap[type] || type
}

const getTypeTagType = (type) => {
  const tagTypeMap = {
    0: 'primary',    // 菜单权限 - 蓝色
    1: 'success'     // 按钮权限 - 绿色
  }
  return tagTypeMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '正常',
    0: '禁用'
  }
  return statusMap[status] || status
}

// 加载权限数据
const loadPermissions = async () => {
  loading.value = true
  try {
    const response = await sysPermissionQueryAPI()
    if (response.data && response.code === 0) {
      permissions.value = response.data
    } else {
      ElMessage.error('加载权限数据失败')
    }
  } catch (error) {
    ElMessage.error('加载权限数据失败')
  } finally {
    loading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  editingPermission.value = null
  form.value = {
    permissionName: '',
    permissionCode: '',
    url: '',
    type: 0,
    parentId: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑权限
const editPermission = (permission) => {
  isEdit.value = true
  editingPermission.value = permission
  form.value = { 
    permissionName: permission.permissionName,
    permissionCode: permission.permissionCode,
    url: permission.url || '',
    type: permission.type,
    parentId: permission.parentId || '',
    status:permission.status
  }
  dialogVisible.value = true
}


// 删除权限
const deletePermission = async (permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${permission.permissionName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await sysPermissionDeleteAPI(permission.id)
    if (response.data && response.code ===0) {
      ElMessage.success('权限删除成功')
      loadPermissions()
    } else {
      ElMessage.error('删除权限失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    submitLoading.value = true
    let response
    if (isEdit.value) {
      // 编辑权限
      response = await sysPermissionUpdateAPI({
        ...form.value,
        id: editingPermission.value?.id
      })
    } else {
    // 添加新权限
      response = await sysPermissionCreateAPI(form.value)
    }
    
    if (response.data && response.code ===0) {
      ElMessage.success(isEdit.value ? '权限更新成功' : '权限添加成功')
      dialogVisible.value = false
      loadPermissions()
  } else {
      ElMessage.error(isEdit.value ? '权限更新失败' : '权限添加失败')
    }
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error(isEdit.value ? '权限更新失败' : '权限添加失败')
  } finally {
    submitLoading.value = false
  }
}


onMounted(() => {
  // 初始化数据
  loadPermissions()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 16px;
}
</style>
